#include "jobmanagement.h"
#include "ui_jobmanagement.h"
#include <QPushButton>
#include <QGroupBox>
#include <QCheckBox>

JobManagement::JobManagement(QSqlDatabase &database, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::JobManagement),
    addRecordButton(nullptr),
    citiesGroupBox(new QGroupBox("", this)),
    query(database),
    companiesMap(mapGenerator("投递意向", "公司名称")),
    citiesMap(mapGenerator("城市", "城市名称"))
{
    this->ui->setupUi(this);
    this->addRecordButton = this->ui->buttonBox->addButton("Add", QDialogButtonBox::ActionRole);
    //this->ui->buttonBox->button(QDialogButtonBox::Cancel)->setVisible(false);

    this->ui->companyNameComboBox->addItems(QStringList(companiesMap.keys()));
    QGridLayout *citiesGroupBoxLayout = new QGridLayout(this->citiesGroupBox);
    int citiesComboBoxCount = 0;
    for (const QString &city : citiesMap.keys())
    {
        QCheckBox *cityCheckBox = new QCheckBox(city, this);
        this->citiesCheckBoxes.insert(city, cityCheckBox);
        connect(cityCheckBox, QCheckBox::clicked, this, JobManagement::onInfoUpdated);
        citiesGroupBoxLayout->addWidget(cityCheckBox, citiesComboBoxCount / 3, citiesComboBoxCount % 3);
        citiesComboBoxCount++;
    }
    this->ui->infoFrameLayout->addWidget(this->citiesGroupBox, 4, 1);

    query.exec("select 职位意向.*, 投递意向.公司名称, group_concat(城市.城市名称) as 工作城市 "
               "from 职位意向 "
               "left join 投递意向 on 职位意向.公司ID = 投递意向.ID "
               "left join 职位城市 on 职位意向.ID = 职位城市.职位ID "
               "left join 城市 on 职位城市.城市ID = 城市.ID "
               "group by 职位意向.ID "
               "order by 公司ID, 志愿顺序 asc ");
    while (query.next())
    {
        int id = query.value("ID").toInt();
        QString companyName = query.value("公司名称").toString();
        int aspiration = query.value("志愿顺序").toInt();
        QString job = query.value("职位名称").toString();
//        QString requirement = query.value("职位要求和介绍").toString();
        QString cities = query.value("工作城市").toString();

        QString labelItem = QString("%1(%2)-%3-%4").arg(companyName).arg(aspiration).arg(job).arg(cities);
        listLabelToId.insert(labelItem, id);
        this->ui->listWidget->addItem(labelItem);
    }

    this->clearInfoFrame(this->ui->listWidget->count() == 0);
    this->setEditMode(false);

    connect(this->addRecordButton, QPushButton::clicked, this, JobManagement::onAddButtonClicked);
    connect(this->ui->buttonBox->button(QDialogButtonBox::Save), QPushButton::clicked, this, JobManagement::onSaveButtonClicked);
    connect(this->ui->buttonBox->button(QDialogButtonBox::Cancel), QPushButton::clicked, this, JobManagement::onCancelButtonClicked);
    connect(this->ui->buttonBox->button(QDialogButtonBox::Close), QPushButton::clicked, this, JobManagement::done);
}

JobManagement::~JobManagement()
{
    delete ui;
}

void JobManagement::clearInfoFrame(bool frozenFlag)
{
    this->ui->companyNameComboBox->setCurrentIndex(0);
    this->ui->companyNameComboBox->setDisabled(frozenFlag);
    this->ui->aspirationSpinBox->setValue(1);
    this->ui->aspirationSpinBox->setDisabled(frozenFlag);
    this->ui->jobLineEdit->clear();
    this->ui->jobLineEdit->setDisabled(frozenFlag);
    this->ui->requirementPlainTextEdit->clear();
    this->ui->requirementPlainTextEdit->setDisabled(frozenFlag);
    this->clearCitiesCheckBoxes(frozenFlag);
    //this->ui->buttonBox->button(QDialogButtonBox::Save)->setEnabled(false);
    this->setAddMode(false);
    this->setEditMode(false);
}

void JobManagement::clearCitiesCheckBoxes(bool frozenFlag)
{
    for (QCheckBox *checkBox : this->citiesCheckBoxes.values())
    {
        checkBox->setChecked(false);
        checkBox->setDisabled(frozenFlag);
    }
}

QMap<QString, int> JobManagement::mapGenerator(const QString &tableName, const QString &fieldName)
{
    QSqlQuery query(this->query);
    QMap<QString, int> result;
    query.exec(QString("select ID, %1 from %2 order by ID").arg(fieldName).arg(tableName));
    while (query.next())
    {
        int id = query.value("ID").toInt();
        QString text = query.value(fieldName).toString();
        result.insert(text, id);
    }
    return result;
}

QStringList JobManagement::checkedCities()
{
    QStringList result;
    for (QCheckBox *checkBox : citiesCheckBoxes)
        if (checkBox->checkState() == Qt::Checked)
            result.push_back(checkBox->text());
    return result;
}

void JobManagement::onListWidgetCurrentTextChanged(QString text)
{
    qDebug() << "onListWidgetCurrentTextChanged";
    auto it = listLabelToId.find(text);
    if (it != listLabelToId.end())
    {
        QSqlQuery query(this->query);
        query.exec(QString(
                       "select 职位意向.*, 投递意向.公司名称, 城市.城市名称 as 工作城市 "
                       "from 职位意向 "
                       "left join 投递意向 on 职位意向.公司ID = 投递意向.ID "
                       "left join 职位城市 on 职位意向.ID = 职位城市.职位ID "
                       "left join 城市 on 职位城市.城市ID = 城市.ID "
                       "where 职位意向.ID = %1 "
                       "order by 城市.ID asc ")
                   .arg(*it));

        bool firstTimeFlag = true;
        this->clearCitiesCheckBoxes();
        while (query.next())
        {
            if (firstTimeFlag)
            {
                QString companyName = query.value("公司名称").toString();
                int aspiration = query.value("志愿顺序").toInt();
                QString job = query.value("职位名称").toString();
                QString requirement = query.value("职位要求和介绍").toString();

                this->ui->companyNameComboBox->setCurrentText(companyName);
                this->ui->aspirationSpinBox->setValue(aspiration);
                this->ui->jobLineEdit->setText(job);
                this->ui->requirementPlainTextEdit->setPlainText(requirement);

                firstTimeFlag = false;
            }
            QString city = query.value("工作城市").toString();
            auto iCity = citiesCheckBoxes.find(city);
            if (iCity != citiesCheckBoxes.end())
                (*iCity)->setChecked(true);
        }
    }
    this->setEditMode(false);
}
void JobManagement::onInfoUpdated()
{
    qDebug() << "onInfoUpdated";
    this->setEditMode();
}
void JobManagement::onAddButtonClicked()
{
    qDebug() << "onAddButtonClicked";

    this->setAddMode();
    this->setEditMode();
}
void JobManagement::onSaveButtonClicked()
{
    qDebug() << "onSaveButtonClicked";
    QSqlQuery query(this->query);
    bool queryResult = false;
    int id = 0;
    QString companyName = this->ui->companyNameComboBox->currentText();
    int companyId = this->companiesMap[companyName];
    int aspiration = this->ui->aspirationSpinBox->value();
    QString job = this->ui->jobLineEdit->text();
    QString requirement = this->ui->requirementPlainTextEdit->toPlainText();
    QStringList cities = this->checkedCities();
    //如果是在添加状态下
    if (this->isAddMode())
    {
        queryResult = query.exec(QString("insert into 职位意向(ID) values(NULL)"));
        qDebug() <<"1" << queryResult;
        if (!queryResult)
            return;

        QString text = "<新建项目标>";
        this->ui->listWidget->setDisabled(false);        
        this->ui->listWidget->setCurrentItem(new QListWidgetItem(text, this->ui->listWidget));

        queryResult = query.exec(QString("select seq from sqlite_sequence where name = '职位意向'"));
        qDebug() <<"2" << queryResult;
        if (!queryResult)
            return;
        query.next();        
        listLabelToId.insert(text, query.value("seq").toInt());
    }
    //如果是在修改状态下
    auto iId = listLabelToId.find(this->ui->listWidget->currentItem()->text());
    if (iId == listLabelToId.end())
    {
        qDebug() << "无此行！";
        return;
    }
    id = *iId;

    //增加信息
    queryResult = query.exec(QString(
                        "update 职位意向 "
                        "set 公司ID = %1, "
                        "志愿顺序 = %2, "
                        "职位名称 = '%3', "
                        "职位要求和介绍 = '%4' "
                        "where 职位意向.ID = %5 "
                        )
                    .arg(companyId)
                    .arg(aspiration)
                    .arg(job)
                    .arg(requirement)
                    .arg(id)
               );
    qDebug() <<"3" <<companyId<<aspiration<<job<<requirement<<id<< queryResult;
    if (!queryResult)
        return;
    QString labelItem = QString("%1(%2)-%3-%4").arg(companyName).arg(aspiration).arg(job).arg(cities.join(','));
    auto iItem = listLabelToId.find(this->ui->listWidget->currentItem()->text());
    if (iItem != listLabelToId.end())
        listLabelToId.erase(iItem);
    this->ui->listWidget->currentItem()->setText(labelItem);
    listLabelToId.insert(labelItem, id);
    qDebug() << labelItem<<listLabelToId[labelItem];

    //增加城市信息
    queryResult = query.exec(QString("delete from 职位城市 where 职位ID = %1").arg(id));
    qDebug() <<"4" << queryResult;
    if (!queryResult)
        return;
    for (const QString &city : cities)
    {
        queryResult = query.exec(QString("insert into 职位城市 values(%1, %2) ").arg(id).arg(this->citiesMap[city]));
        qDebug() <<QString("5:%1").arg(city) << queryResult;
        if (!queryResult)
            return;
    }


    this->setAddMode(false);
    this->setEditMode(false);
}

void JobManagement::onCancelButtonClicked()
{
    qDebug() << "onCancelButtonClicked";


    this->setEditMode(false);

    if (this->isAddMode())
    {
        this->setAddMode(false);    
        this->ui->listWidget->setCurrentRow(0);
    }
    this->onListWidgetCurrentTextChanged(this->ui->listWidget->item(this->ui->listWidget->currentRow())->text());
}

void JobManagement::setEditMode(bool editMode)
{
    this->ui->buttonBox->button(QDialogButtonBox::Save)->setEnabled(editMode);
    this->ui->buttonBox->button(QDialogButtonBox::Cancel)->setVisible(editMode);
    this->ui->buttonBox->button(QDialogButtonBox::Close)->setVisible(!editMode);
    this->addRecordButton->setEnabled(!editMode);
    this->ui->listWidget->setDisabled(editMode);
}
